/**
 * @Title: AppPay.java
 * @Package Pay
 * @Description: TODO(用一句话描述该文件做什么)
 * @author STIVEN
 * @date 2018年10月9日
 * @version V1.0
 */
package com.taxsearch.controller.pay;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.taxsearch.constant.HotelDataParam;
import com.taxsearch.controller.room.RoomManageController;
import com.taxsearch.dao.PayMapper;
import com.taxsearch.util.ApiJsonErr;
import com.taxsearch.util.ApiJsonRet;
import com.taxsearch.util.DbUtil;
import com.taxsearch.util.payuntil.Hc;
import com.taxsearch.util.payuntil.HttpClientUtil;
import com.taxsearch.util.payuntil.MD5;
import com.taxsearch.util.payuntil.PageData;
import com.taxsearch.util.roomutil.RoomUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;


import sun.misc.BASE64Decoder;

/**
 * @ClassName: AppPay
 * @Description: TODO(支付和授权期获取)
 * @author STIVEN
 * @date 2018年10月9日
 *
 */
@Controller
@RequestMapping("/HotelAndroid")
public class AppPay {
	// 日志
	public static final Logger logger = LogManager.getLogger(RoomManageController.class);
	// 统一返回结果
	Object result;
	@Autowired
	private PayMapper payMapper;
	//String json="{\"code\":\"0\",\"info\":[{\"dm\":\"2701T999901126\",\"name\":\"某某测试宾馆1\",\"police\":\"5110280117\",\"taxcode\":\"91511028323407614D\",\"userid\":\"US2016092756004210\",\"xgrq\":\"2018-10-12 17:03:46.0\",\"yxqq\":\"2017-11-13 00:00:00.0\",\"yxqz\":\"2017-11-13 00:00:00.0\"},{\"dm\":\"2701T999901126\",\"name\":\"某某测试宾馆6\",\"police\":\"5101000859\",\"taxcode\":\"5101000859\",\"userid\":\"US2016122959042957\",\"xgrq\":\"2017-02-13 17:09:26.0\",\"yxqq\":\"2017-02-13 17:09:26.0\",\"yxqz\":\"2017-02-13 17:09:26.0\"},{\"dm\":\"2701T200501057\",\"name\":\"某某测试宾馆4\",\"police\":\"5101000562\",\"taxcode\":\"5101000562\",\"userid\":\"US2016091841050798\",\"xgrq\":\"2017-02-17 13:37:54.0\",\"yxqq\":\"2017-02-17 13:37:54.0\",\"yxqz\":\"2017-02-17 13:37:54.0\"},{\"dm\":\"2701T200501056\",\"name\":\"某某测试宾馆4\",\"police\":\"5101000562\",\"taxcode\":\"5101000562\",\"userid\":\"US2016091841050798\",\"xgrq\":\"2017-02-17 13:37:54.0\",\"yxqq\":\"2017-02-17 13:37:54.0\",\"yxqz\":\"2017-02-17 13:37:54.0\"},{\"dm\":\"2701T239901081\",\"name\":\"某某测试宾馆4\",\"police\":\"5101000562\",\"taxcode\":\"5101000562\",\"userid\":\"US2016091841050798\",\"xgrq\":\"2017-02-17 13:37:54.0\",\"yxqq\":\"2017-02-17 13:37:54.0\",\"yxqz\":\"2017-02-17 13:37:54.0\"},{\"dm\":\"2701T230801048\",\"name\":\"某某测试宾馆2\",\"police\":\"5101000386\",\"taxcode\":\"5101000386\",\"userid\":\"US2016092756099479\",\"xgrq\":\"2018-10-12 17:11:55.0\",\"yxqq\":\"2018-02-21 00:00:00.0\",\"yxqz\":\"2019-10-12 17:11:55.0\"},{\"dm\":\"2701T230801001\",\"name\":\"某某测试宾馆5\",\"police\":\"5101000838\",\"taxcode\":\"5101000838\",\"userid\":\"US2017022735024734\",\"xgrq\":\"2017-02-27 11:54:41.0\",\"yxqq\":\"2017-02-27 00:00:00.0\",\"yxqz\":\"2018-02-26 00:00:00.0\"},{\"dm\":\"2701T230801048\",\"name\":\"某某测试宾馆3\",\"police\":\"5101000324\",\"taxcode\":\"5101000324\",\"userid\":\"US2016092857011204\",\"xgrq\":\"2017-03-09 10:28:46.0\",\"yxqq\":\"2016-08-24 00:00:00.0\",\"yxqz\":\"2017-08-23 00:00:00.0\"},{\"dm\":\"2701T230801048\",\"name\":\"某某测试宾馆6\",\"police\":\"5101000859\",\"taxcode\":\"5101000859\",\"userid\":\"US2016122959042957\",\"xgrq\":\"2017-03-10 14:15:02.0\",\"yxqq\":\"2015-08-24 00:00:00.0\",\"yxqz\":\"2016-08-23 00:00:00.0\"},{\"dm\":\"2701T239901010\",\"name\":\"某某测试宾馆6\",\"police\":\"5101000859\",\"taxcode\":\"5101000859\",\"userid\":\"US2016122959042957\",\"xgrq\":\"2017-03-10 14:15:02.0\",\"yxqq\":\"2015-11-14 00:00:00.0\",\"yxqz\":\"2016-11-13 00:00:00.0\"},{\"dm\":\"2701T230801001\",\"name\":\"某某测试宾馆2\",\"police\":\"5101000386\",\"taxcode\":\"5101000386\",\"userid\":\"US2016092756099479\",\"xgrq\":\"2017-03-10 14:15:01.0\",\"yxqq\":\"2017-01-01 00:00:00.0\",\"yxqz\":\"2017-12-31 00:00:00.0\"},{\"dm\":\"2701T239901010\",\"name\":\"某某测试宾馆3\",\"police\":\"5101000324\",\"taxcode\":\"5101000324\",\"userid\":\"US2016092857011204\",\"xgrq\":\"2017-03-10 14:15:01.0\",\"yxqq\":\"2017-01-01 00:00:00.0\",\"yxqz\":\"2017-12-31 00:00:00.0\"},{\"dm\":\"2701T230801048\",\"name\":\"某某测试宾馆4\",\"police\":\"5101000562\",\"taxcode\":\"5101000562\",\"userid\":\"US2016091841050798\",\"xgrq\":\"2017-03-10 14:15:01.0\",\"yxqq\":\"2015-08-23 00:00:00.0\",\"yxqz\":\"2016-08-22 00:00:00.0\"},{\"dm\":\"2701T230801001\",\"name\":\"某某测试宾馆4\",\"police\":\"5101000562\",\"taxcode\":\"5101000562\",\"userid\":\"US2016091841050798\",\"xgrq\":\"2017-03-10 14:15:01.0\",\"yxqq\":\"2016-08-19 00:00:00.0\",\"yxqz\":\"2017-08-18 00:00:00.0\"},{\"dm\":\"2701T230801048\",\"name\":\"某某测试宾馆5\",\"police\":\"5101000838\",\"taxcode\":\"5101000838\",\"userid\":\"US2017022735024734\",\"xgrq\":\"2018-10-12 17:20:20.0\",\"yxqq\":\"2016-08-24 00:00:00.0\",\"yxqz\":\"2019-10-12 17:20:20.0\"}]}\r\n" + 
		//	"";
	/**
	 * @Title: analyJson
	 * @Description: TODO(权限查询结果JSON解析为指定JSON)
	 * @param     参数
	 * @return Object    返回类型
	 * @throws Object 
	 */
	@RequestMapping("/selectQuanXian.do")
	@ResponseBody
	public Object analyJson( String data)  {
		//System.out.println(data);
		//String Json=reqYpt(PHONENUMBER);
		Map<String, String> mps = RoomUtil.getJsonMap(data);
		String PHONENUMBER = mps.get("phone");
		//String PHONENUMBER = "18508236265";
		String json=reqYpt( PHONENUMBER);//根据电话号码查询旅馆信息
		List<Map<String, String>> list=new ArrayList<>();//储存结果
		try {
			//获取支付配置文件内容

			Map<String,Object> map = (Map<String,Object>)JSON.parse(json.toString());//转为json
			if(map.get("code").equals("-1")) {
				return new ApiJsonErr("未找到旅馆信息，请联系管理员！");
			}
			else if(map.get("code").equals("-400")) {
				return new ApiJsonErr("服务繁忙，请稍后重试！");

			}else {
				List<String> ListpliceNum=new ArrayList<>();//存储公安编码
				List<Object> resultMap=(List<Object>)JSON.parse(map.get("info").toString());//获取info中json
//				System.out.println("获取的map数据:"+resultMap);
				
				Map<String, String> sMap_temp = new HashMap<>();
				for( Object innerJson:resultMap) {
					Map<String,String> innerMap =new HashMap<>();
					innerMap=(Map<String,String>)JSON.parse(innerJson.toString());
//					System.out.println(innerMap);
					Map<String, String> sMap = new HashMap<>();
					//授权期判定
					SimpleDateFormat format=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
					Integer beginTime=0;
					Integer endTime=0;
					String WLBM_ALL = HotelDataParam.getWlbmAll();
					if(StringUtils.isBlank(WLBM_ALL)) {
						return new ApiJsonErr("预设物料编码归集为空(请设置pay.properties文件WLBM_ALL值)！");

					}
					String[] WLBM_ALl= WLBM_ALL.split(",");//获取所有需要筛选的物料编码归集
					List<String> WLBM_list= Arrays.asList(WLBM_ALl);//
					if(!WLBM_list.contains(innerMap.get("dm"))) {//非筛选出的物料编码不显示前端
						continue;
					}
					// 名字超过限制...
					if(!StringUtils.isBlank(innerMap.get("name"))) {
						if (innerMap.get("name").length() > 7) {
							sMap.put("HOTELNAME", innerMap.get("name")
									.substring(0, 7) + "...");
						}else {
							sMap.put("HOTELNAME", innerMap.get("name"));
						}
					}else {
						sMap.put("HOTELNAME", "未查询到名称");

					}
					//服务期逻辑处理
					if(!StringUtils.isBlank(innerMap.get("yxqq")+"")) {
						String yxqq=(innerMap.get("yxqq")+"");
						if(!"null".equals(yxqq)) {
							//取
							sMap.put("SDATE",innerMap.get("yxqq").substring(0, 10));//有效期起
							beginTime=Integer.parseInt(yxqq.substring(0, 10).replace("-", ""));
									//System.out.println(beginTime);
						}

					}  
					if(!StringUtils.isBlank(innerMap.get("yxqz")+"")) {
						String yxqz=(innerMap.get("yxqz")+"");
						if(!"null".equals(yxqz)) {
							sMap.put("EDATE",innerMap.get("yxqz").substring(0, 10));//有效期止
							endTime=Integer.parseInt(yxqz.substring(0, 10).replace("-", ""));
						}
					}
					// 获取现在的八位时间
					String nowTime = RoomUtil.getEightDateNow();
					int nowTimeInt = Integer.parseInt(nowTime);
                     if(endTime==0) {
                    	 continue;
                     }
					
					if ( nowTimeInt <= endTime&& (endTime - nowTimeInt) > 15) {
						// 正常授权
						sMap.put("code", "0");
					}
					if (nowTimeInt >= beginTime && nowTimeInt <= endTime
							&& (endTime - nowTimeInt) <= 15) {
						// 授权不足十五天
						sMap.put("code", "1");
					}
					if (nowTimeInt > endTime) {
						// 授权已过期
						sMap.put("code", "98");
					}
					
					
					//传值
//					if(ListpliceNum.contains(innerMap.get("police"))) {//排除重复
//						continue;
//					}
//					ListpliceNum.add(innerMap.get("police"));
					
					
					sMap.put("PHONENUMBER",PHONENUMBER);
					sMap.put("STATIONID",innerMap.get("police"));
					sMap.put("HOTELNAMELONG",innerMap.get("name"));
					sMap.put("CUSTOMERID","");
					sMap.put("TAXCODE",innerMap.get("taxcode"));
					sMap.put("USERID",innerMap.get("userid"));
					Map<String, String> mapxz=payMapper.selectXZByStationId(innerMap.get("police"));//获取旅馆性质A01正规旅馆 A03非正规旅馆
					//System.out.println("=="+mapxz);
					String xz="";
					if(mapxz!=null) {
						xz=mapxz.get("YEWULBBM");//旅馆性质
					}
					sMap.put("HOTELXZ", xz);

					if("01".equals(xz)) {//正规旅馆
						sMap.put("HOTELPICE",HotelDataParam.getRegHotle_PayPice());//服务费
						sMap.put("HOTElWLBM",HotelDataParam.getRegHotle_WLBM());//物料编码
					}else{//非正规旅馆
						sMap.put("HOTELPICE",HotelDataParam.getNoRegHotle_PayPice());//服务费
						sMap.put("HOTELWLBM",HotelDataParam.getNoRegHotle_WLBM());//物料编码

					}
					
					/*2019/01/22进行到期时间的去重 取最大值*/
					if(ListpliceNum.contains(innerMap.get("police"))) {//排除重复
						if(Integer.parseInt(sMap_temp.get("EDATE").substring(0, 10).replace("-", "")) < endTime) {
							list.remove(sMap_temp);
							sMap_temp = sMap;
						}else {
							continue;
						}
					}else {
						sMap_temp = sMap;
					}
					ListpliceNum.add(innerMap.get("police"));
					
					list.add(sMap);
				}
				
				System.out.println(list);
			}
			result = new ApiJsonRet("200", list);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("analyJson-发生错误!!!!!!!!!!!!!!!!!!!!!!!!！"+new Date(), e);
			result =  new ApiJsonErr("服务器繁忙,请稍后再试！");
		}
		return result;
	}
	/**
	 * 
	 * @Title: reqYpt
	 * @Description: TODO(查询服务期和旅馆信息)
	 * @param    PHONENUMBER 参数
	 * @return void    返回类型
	 */
	public String reqYpt(String PHONENUMBER){
		String str = "";
		String para="<phone>"+PHONENUMBER+"</phone><dm>2701T230101002</dm>";
		try{

			//获取云平台查询接口地址
			String ypt_reqUrl=HotelDataParam.getYpt_reqUrl();
			PageData params=new PageData();
			StringBuffer sb=new StringBuffer();
			sb.append("<SCJS sid=\"SCJS_YPT_EXPIRE\">");
			sb.append("<id>20160909000001</id>");
			sb.append("<body>");
			sb.append(para+"</body></SCJS>");
			params.put("id", "20160909000001");
			params.put("body", sb.toString());
			params.put("sign", MD5.sign(sb.toString(), "6q3b6a4je2rmaz37nirpqz373xs9fewe", "utf-8"));
			Hc hc=new Hc();
			HttpClient httpClient=new HttpClient();
			HttpConnectionManagerParams managerParams = httpClient
					.getHttpConnectionManager().getParams();
			// 设置连接超时时间(单位毫秒)
			managerParams.setConnectionTimeout(10000);
			// 设置读数据超时时间(单位毫秒)
			managerParams.setSoTimeout(10000);
			HttpClientUtil httpClientUtil=new HttpClientUtil(ypt_reqUrl,params,httpClient);
			hc=httpClientUtil.invokePost();
			if(hc.getStatus()==200&&!"-100".equals(hc.getRespon())&&!"-200".equals(hc.getRespon())&&!"-300".equals(hc.getRespon())){
				str = getFromBase64(new String(hc.getRespon()));
			}else{
				if(hc.getStatus()==200){
					logger.debug("请求失败： " + hc.getRespon());

				}else{
					logger.debug( "请求失败： httpStatus: " + hc.getStatus());

				}
			}
			return str;
		}catch (Exception e){
			logger.error("reqYpt -发生错误!!!!!!!!!!!!!!!!!!!!!!!!！"+new Date(), e);
			throw new RuntimeException("网络繁忙请稍后重试！");

		}
	}
	/**
	 * @Title: updateYpt接口
	 * @Description: TODO(更新服务期 --停用)
	 * @param     参数data json数据 包含DATA  支付流水 HOTELWLBM 物料编码 userId  
	 * @return  Object  返回类型
	 */
	/*
	@RequestMapping("/updateYpt.do")
	@ResponseBody
	public Json  updateYpt(String data){
		Json jsonResult=new Json();
		String userId = "";//
		String DATA = "";//支付流水号
		String HOTELWLBM="";//物料编码
		try{
			Properties p=new Properties();
			p.load(AppPay.class.getClassLoader().getResourceAsStream("pay.properties"));
			//获取云平台查询接口地址
			String ypt_updateUrl=p.getProperty("ypt_updateUrl");
			Map<String, String> mps = RoomUtil.getJsonMap(data);
			userId = mps.get("UERID");
			DATA = mps.get("DATA");//支付流水
			HOTELWLBM=mps.get("HOTELWLBM");//物料编码
			String str = "";
			//	String para="<userid>"+userId+"</userid><dm>"+HOTELWLBM+"</dm>";
			String para="<userid>"+userId+"</userid><dm>2701T230801048" + 
					"</dm>";

			System.out.println("============"+data);
			System.out.println("============"+para);
			PageData params=new PageData();
			StringBuffer sb=new StringBuffer();
			sb.append("<SCJS sid=\"SCJS_YPT_UP_EXPIRE\">");
			sb.append("<id>20160909000001</id>");
			sb.append("<body>");
			sb.append(para+"</body></SCJS>");
			params.put("id", "20160909000001");
			params.put("body", sb.toString());
			params.put("sign", MD5.sign(sb.toString(), "6q3b6a4je2rmaz37nirpqz373xs9fewe", "utf-8"));
			Hc hc=new Hc();
			HttpClient httpClient=new HttpClient();
			HttpClientUtil httpClientUtil=new HttpClientUtil(ypt_updateUrl,params,httpClient);
//			System.out.println("++++++++++++++++++>>>>>>>>>>>>>>>>>>>"+ypt_updateUrl);
			hc=httpClientUtil.invokePost();
			if(hc.getStatus()==200&&!"-100".equals(hc.getRespon())&&!"-200".equals(hc.getRespon())&&!"-300".equals(hc.getRespon())){
				str = getFromBase64(new String(hc.getRespon()));
				Map<String, String> mapRt = RoomUtil.getJsonMap(str);
				result=new ApiJsonRet("200", mapRt);
			}else{
				if(hc.getStatus()==200){
					logger.debug("请求失败： " + hc.getRespon());
				}else{//请求失败
					logger.debug( "请求失败： httpStatus: " + hc.getStatus());
				}
				doSaveErro(userId,HOTELWLBM,DATA,"1","缴费失败【数据未更新】,更新服务期失败云平台返回值1:"+str+"===时间"+new Date());//异常订单信息存储到PAY_RECORD表
				jsonResult.setMsg("缴费失败");
				jsonResult.setSuccess(false);
//				System.out.println(jsonResult);
				return jsonResult;
			}
			if(!StringUtils.isBlank(str)) {
				Map<String,Integer>resultMap=(Map<String,Integer>)JSON.parse(str.toString());//获取更新结果
				if(!"0".equals(resultMap.get("code")+"")) {//记录失败订单

					doSaveErro(userId,HOTELWLBM,DATA,"1","缴费失败【数据未更新】,更新服务期失败云平台返回值2:"+str+"===时间"+new Date());//异常订单信息存储到PAY_RECORD表

					jsonResult.setMsg("缴费失败【数据未更新】，请拨打95113与联系客服！");
					jsonResult.setSuccess(false);
					return jsonResult;
				}else {
					doSaveErro(userId,HOTELWLBM,DATA,"1","缴费失败【数据未更新】,更新服务期失败云平台返回值3:"+str+"===时间"+new Date());//异常订单信息存储到PAY_RECORD表
					jsonResult.setMsg("缴费失败【数据未更新】，请拨打95113与联系客服！");
					jsonResult.setSuccess(true);
					return jsonResult;
				}
			}else {
				doSaveErro(userId,HOTELWLBM,DATA,"1","缴费失败【数据未更新】,更新服务期失败云平台返回值为4："+str+"===时间"+new Date());//异常订单信息存储到PAY_RECORD表
				jsonResult.setMsg("缴费失败【数据未更新】，请拨打95113与联系客服！");
				jsonResult.setSuccess(false);
				return jsonResult;

			}
		}catch (Exception e){//同时记录失败订单
			doSaveErro(userId,HOTELWLBM,DATA,"1","缴费失败【数据未更新】,更新服务期失败时间"+new Date());//异常订单信息存储到PAY_RECORD表
			jsonResult.setMsg("缴费失败【数据未更新】，请拨打95113与联系客服！");
			logger.error("updateYpt -发生错误!!!!!!!!!!!!!!!!!!!!!!!!！"+new Date(), e);

			jsonResult.setSuccess(false);
//			System.out.println(jsonResult);
			e.printStackTrace();

		}
		return jsonResult;
	}
	*/
	/**
	 * @Title: doSaveErro
	 * @Description: TODO(异常订单信息存储到PAY_RECORD表)
	 * @param @param userId
	 * @param @param DATA
	 * @param @param STATUS
	 * @param @param BZ    参数
	 * @return void    返回类型
	 */
	public void doSaveErro(String userId,String HOTELWLBM,String DATA,String STATUS,String BZ) {
		Map<String,String> map=new HashMap<>();
		map.put("UERID", userId);
		map.put("DATA", DATA);
		map.put("STATUS", STATUS);
		map.put("BZ", BZ);
		map.put("HOTELWLBM", HOTELWLBM);

		try {
			System.out.println("=====测试map"+map);
			DbUtil.setDb("1");
			payMapper.insertPayRecord(map);
		}catch (Exception e) {
			e.printStackTrace();
			logger.debug("doSaveErro存储支付失败异常订单信息错误 ！时间："+new Date());
		}
	}
	/**
	 * 
	 * @Title: getFromBase64
	 * @Description: TODO(Base64转换)
	 * @param @param s
	 * @param @return    参数
	 * @return String    返回类型
	 */
	public static String getFromBase64(String s) {
		byte[] b = null;
		String result = null;
		if (s != null) {
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				b = decoder.decodeBuffer(s);
				result = new String(b, "UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * 
	* @Title: doSavePayRecord
	* @Description: TODO(存储支付返回数据)
	* @param     参数
	* @return void    返回类型
	 */
	@RequestMapping("/savePaying")
	@ResponseBody
	public void doSavePayRecord(String data) {
		try {
		Map<String, String> mps = RoomUtil.getJsonMap(data);
		Map<String,String> map=new HashMap<>();//
		map.put("payid", mps.get("payid"));
		map.put("qrNo", mps.get("qrNo"));
		map.put("ddid", mps.get("ddid"));
		map.put("msg", mps.get("msg"));
		map.put("ZFFS",mps.get("zffs"));
		DbUtil.setDb("1");

		payMapper.insertPayRecord(map);
		} catch (Exception e) {
			logger.debug("doSavePayRecord存储支付订单信息错误 ！时间："+new Date());

		}
	}

}


